package com.jetinno.file;

import android.app.Dialog;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;

/**
 * Created by zhangyuncai on 2023/9/21.
 */
public class CommonCharAdapter extends RecyclerView.Adapter<CommonCharAdapter.CommonCharViewHolder> {

    private final List<String> mDatas;
    private final EditText editText;
    private final Dialog dialog;

    public CommonCharAdapter(Dialog dialog, List<String> mDatas, EditText editText) {
        this.dialog = dialog;
        this.mDatas = mDatas;
        this.editText = editText;
    }

    @NonNull
    @Override
    public CommonCharViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_commonchar_adapter, viewGroup, false);
        return new CommonCharViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CommonCharViewHolder viewHolder, int i) {
        TextView tv_commonchar_content = viewHolder.itemView.findViewById(R.id.tv_commonchar_content);
        String content = mDatas.get(i);
        tv_commonchar_content.setText(content);
        tv_commonchar_content.setOnClickListener(v -> {
            int selectionStart = editText.getSelectionStart();
            int selectionEnd = editText.getSelectionEnd();
            Editable editable = editText.getText();
            editable.delete(selectionStart, selectionEnd);
            editable.insert(selectionStart, content);
            dialog.dismiss();
        });
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    public class CommonCharViewHolder extends RecyclerView.ViewHolder {
        private final View itemView;

        public CommonCharViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
        }
    }
}
